package com.zhouzi.zhaoyang.ui.activity

import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.widget.Toast
import com.afollestad.materialdialogs.MaterialDialog
import com.tencent.wxpayface.IWxPayfaceCallback
import com.tencent.wxpayface.WxPayFace
import com.zhouzi.zhaoyang.R
import com.zhouzi.zhaoyang.base.App
import com.zhouzi.zhaoyang.base.BaseActivity
import com.zhouzi.zhaoyang.bean.OrderDetailBean
import com.zhouzi.zhaoyang.config.JobFinal
import com.zhouzi.zhaoyang.mvp.p.ReturnMoneyActivityPresenter
import com.zhouzi.zhaoyang.mvp.v.IReturnMoneyActivityView
import com.zhouzi.zhaoyang.service.VoiceService
import com.zhouzi.zhaoyang.util.Calculator
import kotlinx.android.synthetic.main.return_cash_activity.etCommercialNO
import kotlinx.android.synthetic.main.return_money_activity.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class ReturnMoneyActivity : BaseActivity(), IReturnMoneyActivityView {

    override fun errorToken() {
        exitToLogin()
    }
    override fun getOrderSuccess(orderDetail: OrderDetailBean?) {
        orderDetail?.let {
            if (refundCheck){

                val voiceService3 = Intent(mContext, VoiceService::class.java)
                voiceService3.putExtra("voiceStr", "请确认是否退款")
                startService(voiceService3)


                MaterialDialog.Builder(this)
                    .title("确认退款？")
                    .content("消费金额："+Calculator.fen2Yuan(orderDetail.realFee!!.toLong())+"元")
                    .positiveText("确认")
                    .negativeText("取消")
                    .onPositive { dialog, which ->

                        Log.e("goodsNo1", goodsNo)
                        var map = mutableMapOf(
                            Pair("outTradeNo", goodsNo),
                            Pair("refundSecret",tvAdminPW.text.toString() )

                        )
                        p.refund(map)

                    }
                    .onNegative { dialog, which ->

                        dialog.dismiss()

                    }
                    .build()
                    .show()

            }else{
                App.instance().printOrderWithReturnMoney(orderDetail!!)
            }

        }

    }

    override fun getOrderFailed(msg: String?) {

        val voiceService3 = Intent(mContext, VoiceService::class.java)
        voiceService3.putExtra("voiceStr", "订单号异常")
        startService(voiceService3)
    }


    var p = ReturnMoneyActivityPresenter()

    init {
        p.attachView(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        p.detachView()
    }

    override fun refundSuccess() {
        val intent3 = Intent(mContext, VoiceService::class.java)
        intent3.putExtra("voiceStr", "退款成功")
        startService(intent3)

        p.getOrder(etCommercialNO.text.toString())

        val activity = Intent(this, MainActivity::class.java)
        startActivity(activity)
        finish()

    }

    override fun refundFailed(msg: String) {
        val intent4 = Intent(mContext, VoiceService::class.java)
        intent4.putExtra("voiceStr", msg)
        startService(intent4)
    }

    override fun showLoadDialog() {
        loadDialog.show()

    }

    override fun dismissLoadDialog() {
        loadDialog.dismiss()

    }

    override fun getLayoutId(): Int {
        return R.layout.return_money_activity
    }

    var serviceIntent = Intent()
    override fun initView() {
        serviceIntent = Intent(mContext, VoiceService::class.java)


        viewClick()

    }

    /*判断回调是否异常*/
    private fun isSuccessInfo(info: Map<*, *>?): Boolean {


        if (info == null) {
            RuntimeException("调用返回为空").printStackTrace()
            return false
        }
        val code = info["return_code"] as String
        val msg = info["return_msg"] as String
        Log.d("response parameter", "response | getWxpayfaceRawdata $code | $msg")
        if (code == null || info.get("rawdata").toString() == null || !code.equals("SUCCESS")) {
            RuntimeException("调用返回非成功信息,return_msg:" + msg + "   ").printStackTrace()
            return false
        }
        return true
    }

    override fun onStart() {
        super.onStart()
        tvAdminPW.requestFocus()
        serviceIntent.putExtra("voiceStr", "请输入管理员密码")
        startService(serviceIntent)

    }

    override fun onResume() {
        super.onResume()
        countDown()

    }

    override fun onPause() {
        super.onPause()
        job?.cancel()
    }

    private var job: Job? = null
    private fun countDown() {
        /*开始倒计时30s退出页面*/
        job = GlobalScope.launch {
            delay(JobFinal.EXECUTE_TIME)
            val intent = Intent(mContext, VoiceService::class.java)
            intent.putExtra("voiceStr", "交易失败")
            startService(intent)
            var activity = Intent(mContext,MainActivity :: class.java)
            startActivity(activity)
            finish()
        }
    }


    override fun onStop() {
        super.onStop()
        if (serviceIntent != null) {
            stopService(serviceIntent)
        }
    }

    private fun viewClick() {
        tvApBtnBack2.setOnClickListener {
            finish()
        }
    }

    var enter = 160
    var goodsNo = "0"
    var refundCheck = false
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {


        Calculator.onKeyEvent(
            when (event?.keyCode) {
                KeyEvent.KEYCODE_NUMPAD_1 -> Calculator.KeyCode._1
                KeyEvent.KEYCODE_NUMPAD_2 -> Calculator.KeyCode._2
                KeyEvent.KEYCODE_NUMPAD_3 -> Calculator.KeyCode._3
                KeyEvent.KEYCODE_NUMPAD_4 -> Calculator.KeyCode._4
                KeyEvent.KEYCODE_NUMPAD_5 -> Calculator.KeyCode._5
                KeyEvent.KEYCODE_NUMPAD_6 -> Calculator.KeyCode._6
                KeyEvent.KEYCODE_NUMPAD_7 -> Calculator.KeyCode._7
                KeyEvent.KEYCODE_NUMPAD_8 -> Calculator.KeyCode._8
                KeyEvent.KEYCODE_NUMPAD_9 -> Calculator.KeyCode._9
                KeyEvent.KEYCODE_NUMPAD_0 -> Calculator.KeyCode._0
                KeyEvent.KEYCODE_NUMPAD_DOT -> Calculator.KeyCode._D
                KeyEvent.KEYCODE_DEL -> Calculator.KeyCode._B
                KeyEvent.KEYCODE_ENTER -> Calculator.KeyCode._E
                else -> return super.onKeyDown(event!!.keyCode, event)
            }
        )


        if ((event?.keyCode == KeyEvent.KEYCODE_ENTER || event?.keyCode == enter)) {

            if (event.getAction() != KeyEvent.ACTION_UP) {

                if (TextUtils.isEmpty(tvAdminPW.text.toString())) {
                    val serviceIntent = Intent(mContext, VoiceService::class.java)
                    serviceIntent.putExtra("voiceStr", "请输入管理员密码")
                    startService(serviceIntent)
                    tvAdminPW.requestFocus()
                    return false
                } else if (TextUtils.isEmpty(etCommercialNO.text.toString())) {
                    etCommercialNO.requestFocus()
                    wxScan()
                    return super.dispatchKeyEvent(event)
                } else {

                    goodsNo = etCommercialNO.text.toString()

                    refundCheck = true
                    p.getOrder(goodsNo)

                    // todo
                    return super.dispatchKeyEvent(event)
                }
            } else {
                return false
            }
        } else {
            return super.dispatchKeyEvent(event)
        }
    }




    private fun wxScan() {

        val scanIntent = Intent(this, VoiceService::class.java)
        scanIntent.putExtra("voiceStr", "请对准上方摄像头扫码")
        startService(scanIntent)

        /*初始化刷脸*/
        WxPayFace.getInstance().initWxpayface(mContext, object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
                Handler(Looper.getMainLooper()).post {
                    if (isSuccessInfo(p0)) {
                        WxPayFace.getInstance().stopCodeScanner()

                        WxPayFace.getInstance().startCodeScanner( object  : IWxPayfaceCallback(){


                            override fun response(info: MutableMap<Any?, Any?>?) {

                                runOnUiThread {
                                    Log.e("startCodeScanner",info.toString())

                                    if (info != null){
                                        var return_code = info.get("return_code")
                                        var return_msg = info.get("return_msg")
                                        var code_msg = info.get("code_msg")
                                        var  resultString = "startCodeScanner, return_code : " + return_code + " return_msg : " + return_msg + " code_msg: " + code_msg

                                        if (code_msg != null){


                                            goodsNo = code_msg.toString()
                                            etCommercialNO.setText(goodsNo)
                                            refundCheck = true
                                            p.getOrder(goodsNo)




                                        }else{
                                            stopService(scanIntent)
                                            val scanIntent2 = Intent(App.mContext, VoiceService::class.java)
                                            scanIntent2.putExtra("voiceStr", "请重新扫码")
                                            startService(scanIntent2)
                                        }


                                    }


                                }




                            }
                        })

                    } else {
                        Toast.makeText(mContext, "初始化失败，请稍后再试", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })




    }



}
